package com.tangji.antenna.bean;

import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.fqgj.common.utils.DateUtil;
import com.jsoniter.any.Any;
import com.tangji.signaltower.bean.MarketDataEntity;
import com.tangji.signaltower.container.DataContainer;
import com.tangji.signaltower.container.ProductDataContainer;
import com.tangji.signaltower.enums.ProductEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jsoniter.JsonIterator;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 把来自服务端的数据封装成事件，便于按顺序处理
 * User: Amarendar
 * Date: 2020/6/5
 * Time: 下午3:41
 */
public class EventFactory {

    private static final Logger log = LoggerFactory.getLogger(EventFactory.class);

    public static long REFERENCE_VALUE;

    static {
        calcReferenceValue();
    }

    public static long calcReferenceValue() {
        String date1 = DateUtil.getDate(new Date());
        String[] date1Arr = date1.split("-");
        int month = Integer.valueOf(date1Arr[1]);
        month = ((month + 2) / 3) * 3 - 3 + 1;
        String yearStr = date1Arr[0];
        String monthStr = String.format("%02d", month);
        String dayStr = "01";
        Date date2 = DateUtil.getDate(yearStr + monthStr + dayStr, "yyyyMMdd");
        log.info("启动计算业务时间差,基准日期:{},REFERENCE_VALUE:{}", DateUtil.getDate(date2, "yyyy-MM-dd"), date2.getTime());
        REFERENCE_VALUE = date2.getTime();
        return date2.getTime();
    }

    /**
     * 数据转换
     *
     * @param provider
     * @param text
     * @param body
     * @return socket数据源
     */
    public static boolean saveDataToQueue(ProviderTypeEnum provider, String text, Any body) {
        Any deserialize = JsonIterator.deserialize(text).get("tick");
        MarketDataEntity marketDataEntity=new MarketDataEntity()
//                .setType(deserialize.get("symbol").toString())
                .setType(deserialize.get("symbol").toString().equals("frxEURUSD")?"F_EUR_USD":"F_GBP_USD")
                .setMarketPrice(deserialize.get("bid").toString())
                .setMarketTimestamp(deserialize.get("epoch").toLong()*1000)
                .setBusinessTime(System.currentTimeMillis());

        long tmp = (System.currentTimeMillis() - marketDataEntity.getMarketTimestamp())/1000;
        log.info("saveDataToQueue收到数据," + provider.getType() + ",delay:{},text:{}", tmp, text);
        if (tmp >= 10) {
            log.error(provider.getType() + ",saveDataToQueue 延迟过大,丢弃数据,delay:{},marketDataEntity:{}", tmp, text);
            return true;
        }

        //四舍五入操作
        ProductEnum productEnum = ProductEnum.getEnumByProductCode(marketDataEntity.getType());
        String price = new BigDecimal(marketDataEntity.getMarketPrice()).setScale(productEnum.getTailNum(), BigDecimal.ROUND_HALF_UP).toPlainString();
        marketDataEntity.setMarketPrice(price);

        DataContainer dataContainer = ProductDataContainer.getDataContainer(ProductEnum.getEnumByProductCode(marketDataEntity.getType()));
        dataContainer.updateLastData(marketDataEntity);
        log.info("saveDataToQueue塞入数据,delay:{},marketDataEntity:{}", tmp, JSON.toJSONString(marketDataEntity));
        return true;
    }


}
